package org.jetnuke.modules.blog;

import org.apache.log4j.Logger;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.jforum.dao.UserDAO;
import net.jforum.entities.User;

import org.apache.velocity.VelocityContext;
import org.jetnuke.common.ActionForward;
import org.jetnuke.common.IAction;
import org.jetnuke.common.IAdminInfo;
import org.jetnuke.common.IModuleInfo;
import org.jetnuke.common.IUserInfo;
import org.jetnuke.dao.BlogCategoryDAO;
import org.jetnuke.dao.BlogPostDAO;
import org.jetnuke.dao.DataAccessDriver;
import org.jetnuke.entities.BlogCategory;
import org.jetnuke.entities.BlogPost;
import org.jetnuke.modules.blog.utils.BlogUtils;

//Show last entries from all users!
public class Show implements IAction {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(Show.class);

	public ActionForward exec(HttpServletRequest request,
			HttpServletResponse response, VelocityContext vc, IModuleInfo info,
			String op, IUserInfo ui, IAdminInfo ai) throws Exception {
		if (logger.isDebugEnabled()) {
			logger
					.debug("exec(HttpServletRequest, HttpServletResponse, VelocityContext, IModuleInfo, String, IUserInfo, IAdminInfo) - start"); //$NON-NLS-1$
		}

		BlogPostDAO bpm = DataAccessDriver.getInst().newBlogPostDAO();
		BlogCategoryDAO bcm = DataAccessDriver.getInst().newBlogCategoryDAO();
		UserDAO um = DataAccessDriver.getInst().newUserDAO();
		int last = 20;
		List ls = bpm.retrieveLast(last);
		Iterator it = ls.iterator();
		HashMap mp = new HashMap();
		HashMap cp = new HashMap();
		while (it.hasNext()) {
			BlogPost bp = (BlogPost) it.next();
			int authorID = bp.getAID();
			User user = um.selectById(authorID);
			mp.put(new Integer(authorID), user);
			int postCat = bp.getPOSTCATEGORY();
			BlogCategory bc = bcm.retrieveByPK(postCat);
			cp.put(new Integer(postCat), bc);

		}
		vc.put("ls", ls);
		vc.put("mp", mp);
		vc.put("cp", cp);
		List preLeftBlocks = new ArrayList();
		preLeftBlocks.add(BlogUtils.createStatInfo(vc));
		vc.put("_preBlocks", preLeftBlocks);
		ActionForward returnActionForward = new ActionForward(op, info);
		if (logger.isDebugEnabled()) {
			logger
					.debug("exec(HttpServletRequest, HttpServletResponse, VelocityContext, IModuleInfo, String, IUserInfo, IAdminInfo) - end"); //$NON-NLS-1$
		}
		return returnActionForward;
	}

}
